package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 向套餐表插入一条数据,向套餐菜品表插入n条数据
     *
     * @param setmealDTO
     */
    @Transactional
    @Override
    public void save(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        //插入套餐基础数据,!!!!!!!!并获取主键id!!!!!!!
        setmealMapper.insert(setmeal);
        Long setmealId = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealId));
        setmealDishMapper.insertDishBatch(setmealDishes);
    }

    /**
     * 套餐分页查询
     *
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        //工具类生成分页
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());
        Page<Setmeal> setmealPage = setmealMapper.pageQuery(setmealPageQueryDTO);


        return new PageResult(setmealPage.getTotal(), setmealPage);

        //生成page对象
    }

    /**
     * 批量删除套餐
     *
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {

        //判断套餐状态,如果是售卖状态不能删除
        for (Long id : ids) {
            Setmeal setmeal = setmealMapper.getById(id);
            if (setmeal.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //删除套餐,同时删除套餐中的菜品
        setmealMapper.deleteBatch(ids);
        setmealDishMapper.deleteDishBatch(ids);
    }

    @Override
    public SetmealVO getByIdWithDish(Long id) {
        Setmeal setmeal = setmealMapper.getById(id);
        List<SetmealDish> setmealDishList = setmealDishMapper.getSetmealIdWithDish(id);
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);
        setmealVO.setSetmealDishes(setmealDishList);
        return setmealVO;
    }

    /**
     * 根据id修改套餐数据
     *
     * @param setmealDTO
     */
    @Override
    public void update(SetmealDTO setmealDTO) {
        //修改基础数据
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);
        setmealMapper.update(setmeal);
        Long setmealId = setmeal.getId();

        //修改菜品数据,先删除所有存在的菜品数据,再重新添加
        setmealDishMapper.deleteBySetmealId(setmealId);
        //获取前端传来的菜品数据
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        //给传来的每条数据传一个套餐id
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealId));
        //将修改后的数据重新添加
        setmealDishMapper.insertDishBatch(setmealDishes);
    }

    /**
     * 根据id修改当前状态
     *
     * @param status
     * @param id
     */
    @Override
    public void updateWithStatus(Integer status, Long id) {
        //根据套餐id获取当前关联菜品状态
        if (status == StatusConstant.ENABLE) {
            List<Dish> dishList = dishMapper.selectDishWithSetmeal(id);
            if (dishList.size() > 0 && dishList != null) {
                dishList.forEach(dish -> {
                    if (dish.getStatus() == StatusConstant.DISABLE) {
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.update(setmeal);
    }

    @Override
    public List<Setmeal> getSetmealBycategoryId(Long categoryId) {

        Setmeal setmeal = new Setmeal();
        setmeal.setCategoryId(categoryId);
        setmeal.setStatus(StatusConstant.ENABLE);

        List<Setmeal> setmealList = setmealMapper.list(setmeal);

        return setmealList;
    }

    /**
     * 根据套餐id查询关联菜品
     *
     * @param id
     * @return
     */
    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        String key = "setmealDish_" + id;
        List<DishItemVO> list = (List<DishItemVO>) redisTemplate.opsForValue().get(key);
        if (list != null && list.size() > 0) {
            log.info("从内存查询套餐关联菜品:{}", list);
            return list;
        }
        List<DishItemVO> setmealDishList = setmealMapper.getDishItemBySetmealId(id);
        redisTemplate.opsForValue().set(key, setmealDishList);
        log.info("从数据库查询套餐:{}", setmealDishList);
        return setmealDishList;
    }


}
